<template>
  <div class="map-container">
    <div id="map-container"></div>
    <div class="map-controls">
      <el-select
        v-model="drawType"
        placeholder="选择画笔类型"
        @change="handleDrawTypeChange"
      >
        <el-option label="点" value="point"></el-option>
        <el-option label="线" value="polyline"></el-option>
        <el-option label="面" value="polygon"></el-option>
        <el-option label="清除" value="clear"></el-option>
      </el-select>
      <el-input
        v-model="searchText"
        placeholder="搜索城市"
        @keyup.enter="searchCity"
      ></el-input>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const map = ref(null)
const drawType = ref('')
const searchText = ref('')
const vectorLayer = ref(null)
const markers = ref([])

// 初始化地图
const initMap = () => {
  map.value = new AMap.Map('map-container', {
    zoom: 10,
    center: [116.397428, 39.90923],
    viewMode: '2D',
  })

  // 添加缩放级别变化监听
  map.value.on('zoomend', handleZoomChange)

  // 添加地图点击事件
  map.value.on('click', handleMapClick)
}

// 城市搜索功能
const searchCity = () => {
  AMap.plugin('AMap.Geocoder', () => {
    const geocoder = new AMap.Geocoder({
      city: searchText.value,
    })

    geocoder.getLocation(searchText.value, (status, result) => {
      if (status === 'complete' && result.geocodes.length) {
        const location = result.geocodes[0].location
        map.value.setCenter(location)
        loadVectorData(result.geocodes[0].adcode)
      } else {
        ElMessage.error('未找到该城市')
      }
    })
  })
}

// 加载矢量数据
const loadVectorData = (adcode) => {
  if (vectorLayer.value) {
    map.value.remove(vectorLayer.value)
  }

  vectorLayer.value = new AMap.Object3DLayer()
  // 这里需要根据adcode加载对应的矢量数据
  // 实际项目中需要对接高德地图的矢量数据服务
  map.value.add(vectorLayer.value)
}

// 处理缩放级别变化
const handleZoomChange = () => {
  const zoom = map.value.getZoom()
  // 当缩放级别超过13时显示标记点
  if (zoom > 13 && markers.value.length === 0) {
    addMarkers()
  }

  // 控制矢量图层显示
  if (vectorLayer.value) {
    vectorLayer.value.setVisible(zoom <= 13)
  }
}

// 添加标记点
const addMarkers = () => {
  AMap.plugin(['AMap.MarkerClusterer', 'AMap.ElasticMarker'], () => {
    const cluster = new AMap.MarkerClusterer(map.value, [], {
      gridSize: 80,
      styles: [
        {
          url: 'https://a.amap.com/jsapi_demos/static/images/blue.png',
          size: new AMap.Size(32, 32),
          offset: new AMap.Pixel(-16, -16),
        },
      ],
    })

    // 添加带动画的标记点
    for (let i = 0; i < 50; i++) {
      const marker = new AMap.Marker({
        position: [
          116.397428 + Math.random() * 0.1,
          39.90923 + Math.random() * 0.1,
        ],
        content:
          '<div class="marker-animation"><div class="marker-pulse"></div></div>',
        offset: new AMap.Pixel(-10, -10),
      })

      // 添加弹跳动画
      marker.on('added', () => {
        const el = marker.getContent()
        el.style.transform = 'scale(0)'
        el.style.transition = 'transform 0.3s ease-out'
        setTimeout(() => {
          el.style.transform = 'scale(1)'
        }, 50)

        // 添加点击事件
        marker.on('click', (e) => {
          const infoWindow = new AMap.InfoWindow({
            content: `<div class="marker-info">
              <h4>标记点 ${i + 1}</h4>
              <p>位置: ${e.lnglat.getLng().toFixed(6)}, ${e.lnglat
              .getLat()
              .toFixed(6)}</p>
            </div>`,
            offset: new AMap.Pixel(0, -30),
          })
          infoWindow.open(map.value, e.lnglat)
        })
      })

      markers.value.push(marker)
    }

    cluster.addMarkers(markers.value)
  })
}

// 处理绘图类型变化
const handleDrawTypeChange = (type) => {
  if (type === 'clear') {
    clearDrawings()
    return
  }

  AMap.plugin(['AMap.Overlay', 'AMap.MouseTool'], () => {
    const mouseTool = new AMap.MouseTool(map.value)

    if (type === 'polyline') {
      mouseTool.polyline({
        strokeColor: '#3366FF',
        strokeWeight: 3,
        strokeOpacity: 1,
      })

      mouseTool.on('draw', (e) => {
        const path = e.obj.getPath()
        const distance = calculateDistance(path)
        const infoWindow = new AMap.InfoWindow({
          content: `总距离: ${distance.toFixed(2)}米`,
          offset: new AMap.Pixel(0, -30),
        })
        infoWindow.open(map.value, path[path.length - 1])
      })
    } else if (type === 'polygon') {
      mouseTool.polygon({
        strokeColor: '#FF33FF',
        strokeWeight: 3,
        fillColor: '#FF99FF',
        fillOpacity: 0.2,
      })

      mouseTool.on('draw', (e) => {
        const path = e.obj.getPath()
        const area = calculateArea(path)
        const infoWindow = new AMap.InfoWindow({
          content: `总面积: ${area.toFixed(2)}平方米`,
          offset: new AMap.Pixel(0, -30),
        })
        infoWindow.open(map.value, path[0])
      })
    }

    // 结束测量后自动切换回普通模式
    mouseTool.on('draw', () => {
      mouseTool.close()
      drawType.value = ''
    })
  })
}

// 计算距离
const calculateDistance = (path) => {
  let distance = 0
  for (let i = 1; i < path.length; i++) {
    distance += AMap.GeometryUtil.distance(path[i - 1], path[i])
  }
  return distance
}

// 计算面积
const calculateArea = (path) => {
  return AMap.GeometryUtil.ringArea(path)
}

// 清除绘图
const clearDrawings = () => {
  map.value.getAllOverlays().forEach((overlay) => {
    if (overlay.getType() === 'draw') {
      map.value.remove(overlay)
    }
  })
}

// 处理地图点击事件
const handleMapClick = (e) => {
  // 这里可以添加点击矢量要素显示信息的逻辑
}

onMounted(() => {
  if (!window.AMap) {
    console.error('高德地图JS API未加载')
    ElMessage.error('地图加载失败，请检查控制台')
    return
  }

  // 加载必要的插件
  AMap.plugin(
    [
      'AMap.Geocoder',
      'AMap.DistrictSearch',
      'AMap.MarkerClusterer',
      'AMap.MouseTool',
    ],
    () => {
      initMap()
    }
  )
})
</script>

<style>
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

#map-container {
  width: 100%;
  height: 100%;
}

.map-controls {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  background: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.marker-animation {
  position: relative;
  width: 20px;
  height: 20px;
}

.marker-pulse {
  width: 100%;
  height: 100%;
  background: #1890ff;
  border-radius: 50%;
  box-shadow: 0 0 10px #1890ff;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0.9);
    opacity: 1;
  }
  70% {
    transform: scale(1.3);
    opacity: 0.7;
  }
  100% {
    transform: scale(0.9);
    opacity: 1;
  }
}

.marker-info {
  background: white;
  padding: 10px;
  border-radius: 4px;
  min-width: 200px;
}

.marker-info h4 {
  margin: 0 0 5px 0;
  color: #1890ff;
}
</style>
